﻿/*
 * @版权所有(C): 1999-2021,西安交大捷普网络科技有限公司
 * @FilePath: /JHM/JDA/MonitorPrint/src/PrintUtils/Singleton.h
 * @作者: Yuebb
 * @Date: 2021-01-28 14:27:38
 * @LastEditors: Please set LastEditors
 * @功能描述: 单例模板类
 */
#ifndef SINGLETON_H_
#define SINGLETON_H_
#include <mutex>
#include <memory>
#include <iostream>

/*
 * 不可复制类，继承该类后，子类拥有不可复制功能
 */
class UnCopyable
{
protected:
    UnCopyable() {}
    ~UnCopyable() {}

private:
    UnCopyable(const UnCopyable&) = delete;
    UnCopyable& operator=(const UnCopyable&) = delete;
};

/*
 * 单例模板类，继承后子类为单例模式
 */
template <typename T>
class Singleton : public UnCopyable
{
public:
    /**
     * @description: 获取单例句柄 此函数为线程安全函数
     * @param void
     * @return {T*} 模板类的指针
     */
    static T* getInstance()
    {
        std::lock_guard<std::mutex> gurad(initMutex);
        if (m_instance == nullptr)
        {
            m_instance = new T();
        }
        return m_instance;
    }
    /**
     * @description: 释放单例句柄，需要手动释放，或者程序结束被系统回收资源
     * @param void
     * @return void
     */
    static void destroyInstance()
    {
        if (nullptr != m_instance)
        {
            delete m_instance;
            m_instance = nullptr;
        }
    }

private:
    static T* m_instance;        // 单例句柄
    static std::mutex initMutex; // 初始化线程安全互斥量
};

template <typename T>
T* Singleton<T>::m_instance;

template <typename T>
std::mutex Singleton<T>::initMutex;
#endif
